package com.mailanalyzer.core;

import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;

import com.mailanalyzer.analyzer.Analyzer;
import com.mailanalyzer.dto.FlightData;
import com.mailanalyzer.utils.IOUtils;

/**
 * 
 * @author anibal.kolker
 *
 */
public class Dispatcher {

	private final List<Analyzer> analyzers = new ArrayList<Analyzer>();
	private final List<FlightData> flightData = new ArrayList<FlightData>();

	/**
	 * Dispatches all items in the list to the appended analyzers.
	 * @param list - The list to dispatch.
	 * @return false if an exception is caught. True otherwise.
	 */
	public boolean process(Message[] messages){

		/*int year=0;
		int month=0;*/
		int percent=0;
		int lastShowPercent=0;
		int totalProcessed =-1;

		System.out.println("Starting to process ["+messages.length+"] mails");
		for(Message message : messages){
			String messageText=null;
			try{

				/*year = message.getSentDate().getYear();
				if(month!=message.getSentDate().getMonth()){
					month=message.getSentDate().getMonth();
					//System.out.println(month+"/"+year);
				}*/

				percent=(totalProcessed*100)/messages.length;
				if(percent>(lastShowPercent+9)){
					lastShowPercent=percent;
					System.out.println(percent+"%"+" ["+totalProcessed+"/"+messages.length+"]");
				}



				for(Analyzer analyzer : analyzers){
					if( analyzer.canHandle(message) ){
						try {
							if(messageText ==null)
								messageText =  IOUtils.toString(message.getInputStream());
							FlightData data =analyzer.handle(message, messageText);
							flightData.add(data);
							System.out.println(data);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}

			}
			catch(Exception e){
				e.printStackTrace();
			}
			totalProcessed++;
		}

		return true;
	}


	public void addAnalyzer(Analyzer analyzer){
		this.analyzers.add(analyzer);
	}

	public List<FlightData> getFlightData() {
		return flightData;
	}

}
